"use client";
import { useChat, Message } from "@ai-sdk/react";
import { useParams, useSearchParams } from "next/navigation";
import React, { useEffect, useRef, useState } from "react";
import Outside from "@/components/Outside";
import { chatService } from "@/services/api";
import { useDispatch } from "react-redux";
import { setChatId } from "@/store/reducers/chatIdReducer";

export default function ChatPage() {
  const dispatch = useDispatch();
  const params = useParams();
  const searchParams = useSearchParams();
  // const initialMessage = decodeURIComponent(searchParams.get("message") || "");
  const initialModel = searchParams.get("model") || "deepseek-v3";
  const [selectedModel, setSelectedModel] = useState(initialModel);
  const [showModelList, setShowModelList] = useState(false);
  const [chatHeader, setChatHeader] = useState("新对话");
  const messagesEndRef = useRef<HTMLDivElement>(null);
  const textareaRef = useRef<HTMLTextAreaElement>(null);

  const [isEditing, setIsEditing] = useState(false);
  const [editingTitle, setEditingTitle] = useState(chatHeader);
  const [initialMessages, setInitialMessages] = useState<Message[]>([]);

  interface iMessage {
    id: string;
    content: string;
    role: string;
  }
  const handleHeaderClick = () => {
    setIsEditing(true);
    setEditingTitle(chatHeader);
  };

  const handleInputConfirm = async () => {
    const newTitle = editingTitle.trim();
    if (newTitle !== "") {
      setChatHeader(newTitle);

      // 向后端发送请求
      if (!params.chat_id) return;

      const chatId = Array.isArray(params.chat_id)
        ? params.chat_id[0]
        : params.chat_id;

      try {
        await chatService.updateChatTitle(chatId, newTitle);
        console.log("标题已更新");
      } catch (error) {
        console.error("更新标题失败", error);
        alert("更新标题失败，请重试");
      }
    }

    setIsEditing(false);
  };

  const handleKeyPress = (e: React.KeyboardEvent<HTMLInputElement>) => {
    if (e.key === "Enter") {
      handleInputConfirm();
    }
  };

  // useEffect(() => {
  //   setChatHeader(initialMessage || "新对话");

  //   const mockEvent = {
  //     preventDefault: () => {},
  //     target: { value: initialMessage },
  //   } as unknown as React.ChangeEvent<HTMLTextAreaElement>;

  //   handleInputChange(mockEvent);
  //   handleSubmit(mockEvent);
  // }, []);

  useEffect(() => {
    console.log("useEffect执行", params.chat_id);
    const fetchChatData = async () => {
      if (!params.chat_id) return;

      const chatId = Array.isArray(params.chat_id)
        ? params.chat_id[0]
        : params.chat_id;
      const data = await chatService.getChat(chatId);
      console.log("data", data);

      let initialMessageContent: string | null = null;

      // // 处理 messages 数据并查找初始消息
      // if (Array.isArray(data?.chat?.messages)) {
      //   for (const msg of data.chat.messages) {
      //     // 情况1：存在 initialMessage 字段
      //     if ("initialMessage" in msg) {
      //       initialMessageContent = msg.initialMessage;
      //       break;
      //     }

      //     // 情况2：标准消息结构
      //     if (msg.role && msg.content) {
      //       setInitialMessages(
      //         msg.map((mssg: iMessage) => {
      //           console.log("mssg", mssg);
      //           return {
      //             id: mssg.id,
      //             content: mssg.content,
      //             role: mssg.role,
      //           };
      //         })
      //       );
      //     }
      //   }
      // }

      if (Array.isArray(data?.chat?.messages)) {
        const messages = data.chat.messages;

        for (const item of messages) {
          // 情况1: 存在 initialMessage 字段
          if ("initialMessage" in item) {
            initialMessageContent = item.initialMessage;
            break;
          }

          // 情况2: 是一个二维数组 [[{ role, content }, ...]]
          if (Array.isArray(item) && item.length > 0) {
            const validMessages = item
              .filter((msg) => msg.role && msg.content)
              .map((msg) => ({
                id: msg.id,
                content: msg.content,
                role: msg.role,
              }));

            if (validMessages.length > 0) {
              setInitialMessages(validMessages);
            }
            break; // 找到第一个合法的消息数组后即可退出循环
          }
        }
      }

      // 设置标题
      if (data?.chat?.chatTitle) {
        setChatHeader(data.chat.chatTitle);
      }

      // 如果有 initialMessage 并且没有历史消息，发送初始请求
      if (initialMessageContent && messages.length === 0) {
        append({
          content: initialMessageContent,
          role: "user",
        });
      }
    };

    fetchChatData();
  }, [params.chat_id]);

  useEffect(() => {
    if (params.chat_id) {
      const chatId = Array.isArray(params.chat_id)
        ? params.chat_id[0]
        : params.chat_id;
      dispatch(setChatId(chatId));
    }
  }, [params.chat_id, dispatch]);

  const {
    messages,
    input,
    handleInputChange,
    handleSubmit,
    isLoading,
    append,
  } = useChat({
    api: "/api/chat",
    body: {
      model: selectedModel,
      temperature: 0.7,
      chatId: params.chat_id,
    },
    initialMessages,
    onError: (error) => {
      alert(error.message);
    },
  });

  useEffect(() => {
    messagesEndRef.current?.scrollIntoView({ behavior: "smooth" });
  }, [messages, isLoading]);

  useEffect(() => {
    if (textareaRef.current) {
      textareaRef.current.style.height = "auto";
      textareaRef.current.style.height = `${Math.min(
        textareaRef.current.scrollHeight,
        150
      )}px`;
    }
  }, [input]);

  const handleKeyDown = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
    if (e.key === "Enter" && !e.shiftKey) {
      console.log(e);
      e.preventDefault();
      handleSubmit(e);
    }
  };

  //   // 添加新消息
  // addMessage: async (chatId: string, newMessage: any) => {
  //   const response = await api.post(`/chat/${chatId}/messages`, { newMessage });
  //   return response.data;
  // },
  //监听消息长度并保存
  const saveMessagesToBackend = async () => {
    if (!params.chat_id || isLoading) return;

    // 如果 chat_id 是数组，取第一个元素；否则保持原样，避免ts类型错误
    const chat_id = Array.isArray(params.chat_id)
      ? params.chat_id[0]
      : params.chat_id;

    const res = await chatService.addMessage(chat_id, messages);
    console.log(res);
  };

  useEffect(() => {
    console.log("触发保存");
  }, [params.chat_id]);
  useEffect(() => {
    console.log("触发 useEffect", {
      messages,
      isLoading,
      chatId: params.chat_id,
    });
    if (messages.length > 0 && !isLoading) {
      saveMessagesToBackend();
    }
  }, [messages.length, isLoading, params.chat_id]);

  return (
    <Outside>
      <div className="chat-container">
        <div className="header">
          {isEditing ? (
            <input
              type="text"
              value={editingTitle}
              onChange={(e) => setEditingTitle(e.target.value)}
              onBlur={handleInputConfirm}
              onKeyDown={handleKeyPress}
              autoFocus
              className="chat-header-input"
              style={{ width: "250px", fontSize: "18px" }}
            />
          ) : (
            <div
              className="chat-header"
              title="点击修改对话标题"
              onClick={handleHeaderClick}
            >
              {chatHeader}
            </div>
          )}
          <div className="model-selector">
            <button
              onClick={() => setShowModelList(!showModelList)}
              className="model-toggle"
            >
              {selectedModel}
              <span className={`arrow ${showModelList ? "up" : "down"}`}></span>
            </button>
            {showModelList && (
              <ul className="model-list">
                {["deepseek-v3", "deepseek-r1"].map((model) => (
                  <li
                    key={model}
                    className={model === selectedModel ? "selected" : ""}
                    onClick={() => {
                      setSelectedModel(model);
                      setShowModelList(false);
                    }}
                  >
                    {model}
                  </li>
                ))}
              </ul>
            )}
          </div>
        </div>

        <div className="messages-container">
          <div className="messages">
            {messages.map((message) => (
              <div
                key={message.id}
                className={`message ${message.role}-message`}
              >
                {message.content}
                {message === messages[messages.length - 1] &&
                  message.role === "assistant" && (
                    <span className="typing-cursor"></span>
                  )}
              </div>
            ))}
            {isLoading && (
              <div className="loading-indicator">
                <div className="dot-flashing"></div>
              </div>
            )}
            <div ref={messagesEndRef} />
          </div>
        </div>

        <form onSubmit={handleSubmit} className="input-form">
          <textarea
            ref={textareaRef}
            value={input}
            onChange={handleInputChange}
            onKeyDown={handleKeyDown}
            placeholder="输入消息..."
            rows={1}
            disabled={isLoading}
          />
          <button type="submit" disabled={isLoading}>
            {isLoading ? "发送中..." : "发送"}
          </button>
        </form>

        <style jsx>{`
          .chat-header-input {
            width: 250px;
            height: 25px;
            line-height: 25px;
            box-sizing: border-box;
            padding: 0 10px;
            font-size: 18px;
            border: none;
            outline: none;
            overflow: hidden;
            white-space: nowrap;
            text-overflow: ellipsis;
            color: #333;
            border-radius: 4px;
            background-color: #f0f0f0;
            transition: background-color 0.3s;
          }
          .chat-header {
            font-size: 18px;
            width: 250px;
            height: 25px;
            line-height: 25px;
            box-sizing: "border-box";
            padding: 0 10px;
            overflow: hidden;
            white-space: nowrap;
            text-overflow: ellipsis;
          }
          .chat-header:hover {
            background: #f0f0f0;
            cursor: pointer;
            transition: background-color 0.3s;
            border-radius: 4px;
          }
          .header {
            padding: 1rem;
            background: #fff;
            border-bottom: 1px solid #e0e0e0;
            display: flex;
            justify-content: space-between;
            align-items: center;
          }

          .model-selector {
            position: relative;
          }

          .model-toggle {
            padding: 0.5rem 1rem;
            border: 1px solid #ddd;
            border-radius: 4px;
            background: #fff;
            cursor: pointer;
            display: flex;
            align-items: center;
            gap: 0.5rem;
          }

          .arrow {
            border: solid #666;
            border-width: 0 2px 2px 0;
            display: inline-block;
            padding: 3px;
            transition: transform 0.2s;
          }

          .arrow.down {
            transform: rotate(45deg);
          }

          .arrow.up {
            transform: rotate(-135deg);
          }

          .model-list {
            position: absolute;
            right: 0;
            top: 100%;
            background: #fff;
            border: 1px solid #ddd;
            border-radius: 4px;
            margin-top: 0.5rem;
            min-width: 150px;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
          }

          .model-list li {
            padding: 0.5rem 1rem;
            cursor: pointer;
            transition: background 0.2s;
          }

          .model-list li:hover {
            background: #f5f5f5;
          }

          .model-list .selected {
            background: #e3f2fd;
            color: #1976d2;
          }

          .messages-container {
            flex: 1;
            overflow-y: auto;
            padding: 1rem;
          }

          .messages {
            display: flex;
            flex-direction: column;
            gap: 1rem;
          }

          .message {
            max-width: 80%;
            padding: 1rem;
            border-radius: 1rem;
            word-break: break-word;
          }

          .user-message {
            background: #007bff;
            color: white;
            align-self: flex-end;
          }

          .assistant-message {
            background: #fff;
            border: 1px solid #ddd;
            align-self: flex-start;
          }

          .typing-cursor {
            animation: blink 1s infinite;
            margin-left: 4px;
          }

          .input-form {
            display: flex;
            gap: 1rem;
            padding: 1rem;
            background: #fff;
            border-top: 1px solid #e0e0e0;
          }

          textarea {
            flex: 1;
            padding: 0.8rem;
            border: 1px solid #ddd;
            border-radius: 4px;
            resize: none;
            font-family: inherit;
            font-size: 1rem;
          }

          button[type="submit"] {
            padding: 0.5rem 1.5rem;
            background: #007bff;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            transition: background 0.2s;
          }

          button[type="submit"]:disabled {
            background: #6c757d;
            cursor: not-allowed;
          }

          .loading-indicator {
            padding: 1rem;
            display: flex;
            justify-content: center;
          }

          .dot-flashing {
            position: relative;
            width: 10px;
            height: 10px;
            border-radius: 5px;
            background-color: #999;
            animation: dotFlashing 1s infinite linear alternate;
          }

          .dot-flashing::before,
          .dot-flashing::after {
            content: "";
            display: inline-block;
            position: absolute;
            top: 0;
            width: 10px;
            height: 10px;
            border-radius: 5px;
            background-color: #999;
          }

          .dot-flashing::before {
            left: -15px;
            animation: dotFlashing 1s infinite linear alternate;
            animation-delay: 0s;
          }

          .dot-flashing::after {
            left: 15px;
            animation: dotFlashing 1s infinite linear alternate;
            animation-delay: 0.5s;
          }

          @keyframes blink {
            50% {
              opacity: 0;
            }
          }

          @keyframes dotFlashing {
            0% {
              background-color: #999;
            }
            50%,
            100% {
              background-color: #ddd;
            }
          }
        `}</style>
      </div>
    </Outside>
  );
}
